package uit.cinemainfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class ShowingActivity extends Activity implements Runnable{
	// url to make request
    private static String URL_ALL_FILM = "http://10.0.2.2/efilm/api/films";
    private static String URL_ALL_CINEMA = "http://10.0.2.2/efilm/api/cinemas";
    private static String URL_ALL_SCHE = "http://10.0.2.2/efilm/api/schedules";
    private static String URL_ALL_FILM_VI = "http://10.0.2.2/efilm/api/films_vi";
    private static String URL_ALL_CINEMA_VI = "http://10.0.2.2/efilm/api/cinemas_vi";
    private static String URL_ALL_SCHE_VI = "http://10.0.2.2/efilm/api/schedules_vi";

    // JSON Node names
    private static final String TAG_TRAILER = "trailer";
    private static final String TAG_START = "start";
    private static final String TAG_NOFILM = "nofilm";
    private static final String TAG_NAMEFILM = "namefilm";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_CREDIT = "credit";
    private static final String TAG_SCORE = "score";
    private static final String TAG_IMAGE = "image";
    private static final String TAG_DURATION = "duration";
    private static final String TAG_FAVORITE = "favorite";
    private static final String TAG_KIND = "kind";
    private static final String TAG_NUMVOTE = "numvote";
    
    private static final String TAG_FILMS = "film";
    private static final String TAG_CINEMAS = "cinema";
    private static final String TAG_SCHES = "schedule";
	
    JSONParser jParser = new JSONParser();
    JSONArray films = null;
    JSONArray theaters = null;
    JSONArray schedules = null;
    FilmListViewAdapter adapter;
	ListView listViewHot;
	public ProgressDialog pd;
	DBAdapter db;
	Film[] filmUpdate;
	Theater[] theaterUpdate;
	Schedule[] scheduleUpdate;
	Film[] film;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_showing);	
		
		db = new DBAdapter(this);
		// Loading data in Background Thread
        new LoadData().execute();
        
		//Log.d("Ngon ngu", ShowingActivity.this.getResources().getConfiguration().locale.getLanguage());
		Thread thread = new Thread(this);
		thread.start();
	}
	
	class LoadData extends AsyncTask<String, String, String> {
		/**
         * Before starting background thread Show Progress Dialog
         * */
		
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = ProgressDialog.show(ShowingActivity.this, getResources().getString(R.string.loading), "", true, false);
        }

		@Override
		protected String doInBackground(String... arg0) {
            
           try{
            	String destPath = "/data/data/" + getPackageName() + "/databases/efilm";
            	File f = new File(destPath);
            	if (!f.exists()){
            		CopyDB( getBaseContext().getAssets().open("efilm.db"),
            			new FileOutputStream(destPath));
            	}
            	
            	String destPath_vi = "/data/data/" + getPackageName() + "/databases/vfilm";
            	File f_vi = new File(destPath_vi);
            	if (!f_vi.exists()){
            		CopyDB( getBaseContext().getAssets().open("vfilm.db"),
            			new FileOutputStream(destPath_vi));
            	}
            } catch (FileNotFoundException e) {
            	e.printStackTrace();
            } catch (IOException e) {
            	e.printStackTrace();
            }
           	
           db.open();
           Cursor p = db.getAllShowing();
           film = new Film[p.getCount()];
           int i=0;
           if(p.moveToFirst()){
           	do{
           		film[i] = new Film(p.getString(0), p.getString(1), p.getInt(2), p.getString(3),p.getString(4),p.getString(5),p.getFloat(6),p.getString(7),p.getInt(8),p.getInt(9),p.getString(10),p.getInt(11));
           		i++;
           	}while (p.moveToNext());
           }
           db.close();
           
			return null;
		}
		
		/**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
        	
        	adapter = new FilmListViewAdapter(getApplicationContext(), R.layout.film_listview_item, film);
            listViewHot = (ListView)findViewById(R.id.listFilm);
            listViewHot.setAdapter(adapter);
            listViewHot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            	@Override
            	public void onItemClick(AdapterView av, View v, int position, long id){
            		StartDetail(position);
            	}
    		});
            // dismiss the dialog after getting all products
        	pd.dismiss();
        }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.activity_showing, menu);
	    return true;
	}
	
	public boolean onPrepareOptionsMenu(Menu menu){
		MenuItem item = menu.findItem(R.id.menu_showing);
		item.setEnabled(false);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_coming:
	        	StartComing();
	            return true;
	        case R.id.menu_theater:
	        	StartTheater();
	        	return true;
	        case R.id.menu_news:
	        	StartNews();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public void StartDetail(int position){
		Intent intent = new Intent(ShowingActivity.this, DetailFilmActivity.class);
		intent.putExtra("nofilm", adapter.getItem(position).nofilm);
		startActivity(intent);
	}
	
	public void StartComing(){
		Intent intent = new Intent(ShowingActivity.this, ComingActivity.class);
		startActivity(intent);
	}
	
	public void StartTheater(){
		Intent intent = new Intent(ShowingActivity.this, TheaterActivity.class);
		startActivity(intent);
	}
	
	public void StartNews(){
		Intent intent = new Intent(ShowingActivity.this, ListNewsActivity.class);
		startActivity(intent);
	}

	public void CopyDB(InputStream inputStream, OutputStream outputStream)
		    throws IOException {
		    	byte[] buffer = new byte[1024];
		    	int length;
		    	while ((length = inputStream.read(buffer)) > 0){
		    		outputStream.write(buffer, 0, length);
		    	}
		    	inputStream.close();
		    	outputStream.close();
		    }

	@Override
	public void run() {
		int isWrong = 0;
		// getting JSON string from URL
		JSONObject jsonFilms;
        JSONObject jsonCinemas;
        JSONObject jsonSchedules;
		if(ShowingActivity.this.getResources().getConfiguration().locale.getLanguage().equals("vi")){
			jsonFilms = jParser.makeHttpRequest(URL_ALL_FILM_VI, "GET");
	        jsonCinemas = jParser.makeHttpRequest(URL_ALL_CINEMA_VI, "GET");
	        jsonSchedules = jParser.makeHttpRequest(URL_ALL_SCHE_VI, "GET");
		}else{
			jsonFilms = jParser.makeHttpRequest(URL_ALL_FILM, "GET");
	        jsonCinemas = jParser.makeHttpRequest(URL_ALL_CINEMA, "GET");
	        jsonSchedules = jParser.makeHttpRequest(URL_ALL_SCHE, "GET");
		}

        // Check your log cat for JSON reponse
        //Log.d("All Films: ", jsonCinemas.toString());
        //Log.d("All Films: ", jsonSchedules.toString());

        try {           	
            if (!jsonFilms.isNull(TAG_FILMS)) {

            	films = jsonFilms.getJSONArray(TAG_FILMS);
            	filmUpdate = new Film[films.length()];

                for (int i = 0; i < films.length(); i++) {
                    JSONObject c = films.getJSONObject(i);

                    // Storing each json item in variable
                    filmUpdate[i] = new Film(c.getString(TAG_TRAILER), c.getString(TAG_START), c.getInt(TAG_NOFILM), c.getString(TAG_NAMEFILM), c.getString(TAG_DESCRIPTION),
                    		c.getString(TAG_CREDIT), Float.parseFloat(c.getString(TAG_SCORE)), c.getString(TAG_IMAGE), c.getInt(TAG_DURATION),
                    		c.getInt(TAG_FAVORITE), c.getString(TAG_KIND), c.getInt(TAG_NUMVOTE));
                }
            } else { isWrong = 1; return;}
            
            if (!jsonCinemas.isNull(TAG_CINEMAS)) {

            	theaters = jsonCinemas.getJSONArray(TAG_CINEMAS);
            	theaterUpdate = new Theater[theaters.length()];

                for (int i = 0; i < theaters.length(); i++) {
                    JSONObject c = theaters.getJSONObject(i);

                    // Storing each json item in variable
                    theaterUpdate[i] = new Theater(c.getString("imgtheater"), c.getInt("nocine"), c.getString("namecine"), c.getString("addcine"),
                    		c.getString("telcine"), c.getString("lat"), c.getString("lng"));
                }
            } else { isWrong = 1; return;}
            if (!jsonSchedules.isNull(TAG_SCHES)) {

            	schedules = jsonSchedules.getJSONArray(TAG_SCHES);
            	scheduleUpdate = new Schedule[schedules.length()];

                for (int i = 0; i < schedules.length(); i++) {
                    JSONObject c = schedules.getJSONObject(i);

                    // Storing each json item in variable
                    scheduleUpdate[i] = new Schedule(c.getInt("nosche"), c.getInt("nofilm"), c.getInt("nocine"), c.getString("showtime"), c.getInt("alarm"));
                }
            } else { isWrong = 1; return;}
        } catch (JSONException e) {
            e.printStackTrace();
        }catch(Exception e){
        	Log.d("Detail here: ", e.getMessage());
        }
       // Log.d("wrong here: ", "wroong " + isWrong);
        
        if(isWrong != 1){
       		try{
       			db.open();
	            for(int i = 0; i < filmUpdate.length; i++){		            	
	            	db.updateFilmTable(filmUpdate[i]);		            	
	            }
	            for(int i = 0; i < theaterUpdate.length; i++){		            	
	            	db.updateCinemaTable(theaterUpdate[i]);		            	
	            }
	            for(int i = 0; i < scheduleUpdate.length; i++){		            	
	            	db.updateScheduleTable(scheduleUpdate[i]);		            	
	            }
	            db.close();
            }catch(Exception e){Log.d("Detail here: ", e.getMessage());}        
		
        /*db.open();
        Cursor p = db.getAllShowing();
        film = new Film[p.getCount()];
        int i=0;
        if(p.moveToFirst()){
        	do{
        		film[i] = new Film(p.getString(0), p.getInt(1), p.getString(2),p.getString(3),p.getString(4),p.getFloat(5),p.getString(6),p.getInt(7),p.getInt(8),p.getString(9),p.getInt(10));
        		i++;
        	}while (p.moveToNext());
        }
        db.close(); */       
        //handler.sendEmptyMessage(0);
        }
	}
	
	/*private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

        		adapter = new FilmListViewAdapter(getApplicationContext(), R.layout.film_listview_item, film);
                listViewHot = (ListView)findViewById(R.id.listFilm);
                listViewHot.setAdapter(adapter);
                listViewHot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                	@Override
                	public void onItemClick(AdapterView av, View v, int position, long id){
                		StartDetail(position);
                	}
        		});
                //pd.dismiss();
        }
	};*/
}

